﻿using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using XinLife.Application.Interface;
using XinLife.Core.Model;
using XinLife.Model.Model;

namespace XinLife.Application.Implement
{
    public class OAuthService : BaseService, IOAuthService
    {
        private readonly IHttpClientFactory _httpClientFactory;
        public OAuthService(IBaseRepository baseRepository, IHttpClientFactory httpClientFactory) : base(baseRepository)
        {
            _httpClientFactory = httpClientFactory;
        }

        public async Task<AjaxResult> EditQQAuthAsync(QQAuth qqAuth)
        {
            if (string.IsNullOrWhiteSpace(qqAuth.cId))
            {
                qqAuth.cId = Guid.NewGuid().ToString();

                await _db.Insertable(qqAuth).ExecuteCommandAsync();
                return Success("添加成功");
            }
            else
            {
                await _db.Updateable(qqAuth).ExecuteCommandAsync();
                return Success("修改成功");
            }
        }

        public Task<QQAuth> GetQQAuth(string openId)
        {
            return _db.Queryable<QQAuth>().FirstAsync(t => t.openid == openId);
        }

        public async Task<QQAuth> QQLogin(string code)
        {
            QQAuth qqAuth = new QQAuth();
            //获取token
            string url = $"https://graph.qq.com/oauth2.0/token?grant_type=authorization_code&client_id=102037975&client_secret=QlslQt8AyZw50jEV&code={code}&redirect_uri=https://xin-life.cn/qq&fmt=json";

            var client = _httpClientFactory.CreateClient();

            string res = await client.GetStringAsync(url);
            JObject jobj = JObject.Parse(res);
            if (jobj.ContainsKey("error"))
            {
                string error_code = jobj.Value<string>("error");
                string error_description = jobj.Value<string>("error_description");
                return null;
            }
            qqAuth.access_token = jobj.Value<string>("access_token");
            qqAuth.expires_in = jobj.Value<string>("expires_in");
            qqAuth.refresh_token = jobj.Value<string>("refresh_token");

            //获取openid
            url = $"https://graph.qq.com/oauth2.0/me?access_token={qqAuth.access_token}&fmt=json";
            res = await client.GetStringAsync(url);
            jobj = JObject.Parse(res);
            if (jobj.ContainsKey("ret") && jobj.Value<int>("ret") < 0)
            {
                string msg = jobj.Value<string>("msg");
            }
            qqAuth.openid = jobj.Value<string>("openid");

            //获取用户信息
            url = $"https://graph.qq.com/user/get_user_info?access_token={qqAuth.access_token}&oauth_consumer_key=102037975&openid={qqAuth.openid}";
            res = await client.GetStringAsync(url);

            jobj = JObject.Parse(res);
            if (jobj.Value<int>("ret") < 0)
            {
                string msg = jobj.Value<string>("msg");
            }
            qqAuth.nickname = jobj.Value<string>("nickname");
            qqAuth.gender = jobj.Value<string>("gender");
            qqAuth.province = jobj.Value<string>("province");
            qqAuth.city = jobj.Value<string>("city");
            qqAuth.figureurl_qq = jobj.Value<string>("figureurl_qq");

            var qq = await _db.Queryable<QQAuth>().FirstAsync(t => t.openid == qqAuth.openid);
            if (qq != null)
            {
                qqAuth.cId = qq.cId;
                qqAuth.userId = qq.userId;
            }
            else
            {
                qqAuth.cId = Guid.NewGuid().ToString("N");
            }
            await _db.Storageable(qqAuth).ExecuteCommandAsync();
            return qqAuth;
        }

        public async Task<bool> UpdateUserId(string id, string userId)
        {
            int r = await _db.Updateable<QQAuth>().SetColumns(t => t.userId, userId).Where(t => t.city == id).ExecuteCommandAsync();
            return r > 0;
        }
    }
}
